import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Spin, Tabs, Modal, Select, Input } from 'antd';
import 'moment/locale/zh-cn';
import { SelectC, ModalC } from '../../../comps';
import myStyle from './index.less';
import { BPMNViewer, BPMNEditor } from '../../../comps';
import { diagramXML1 } from '../../../comps/BPMN/editor/moulds/mould1';
import uuid from 'es6-uuid';
const dateFormat = 'YYYY-MM-DD';
const FormItem = Form.Item;
const { TabPane } = Tabs;
const { confirm } = Modal;
const { Option } = Select;
const FormItemLayout = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 8, offset: 0 },
    md: { span: 8, offset: 0 },
    lg: { span: 8, offset: 0 },
    xl: { span: 9, offset: 0 },
    xxl: { span: 8, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 14, offset: 0 },
    md: { span: 14, offset: 0 },
    lg: { span: 14, offset: 0 },
    xl: { span: 14, offset: 0 },
    xxl: { span: 14, offset: 0 },
  },
};
const FormItemLayout1 = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 8, offset: 0 },
    md: { span: 8, offset: 0 },
    lg: { span: 8, offset: 0 },
    xl: { span: 9, offset: 0 },
    xxl: { span: 9, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 14, offset: 0 },
    md: { span: 14, offset: 0 },
    lg: { span: 14, offset: 0 },
    xl: { span: 14, offset: 0 },
    xxl: { span: 14, offset: 0 },
  },
};
const FormItemLayout2 = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 8, offset: 0 },
    md: { span: 8, offset: 0 },
    lg: { span: 8, offset: 0 },
    xl: { span: 9, offset: 0 },
    xxl: { span: 9, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 14, offset: 0 },
    md: { span: 14, offset: 0 },
    lg: { span: 14, offset: 0 },
    xl: { span: 15, offset: 0 },
    xxl: { span: 15, offset: 0 },
  },
};

@connect(({ workFlowM, globalM, loading }) => ({
  workFlowM,
  globalM,
  loading,
}))
@Form.create()
export default class WorkModalC extends PureComponent {
  state = {
    isLoading: false, //点击确定的loading效果
  };

  componentDidMount() {
    if (this.props.modalData.flowType && this.props.type != 'add') {
      this.setState({
        flowChildType: this.props.modalData.flowChildType,
      });
      this.getFlowChildTypeList(this.props.modalData.flowType);
    }
  }
  componentWillUnmount() {
    //离开前清除models数据
    this.props.dispatch({
      type: 'workFlowM/setState',
      payload: {
        flowChildTypeList: [],
      },
    });
  }
  showValue = (value, arr) => {
    if (!arr.length) return value;
    let text = '';
    arr.forEach((item) => {
      if (item.code === value) text = item.value;
    });
    return text;
  };
  getFlowChildTypeList = (e, type) => {
    const {
      dispatch,
      form: { setFieldsValue },
    } = this.props;
    this.setState({
      flowType: e,
    });
    if (type) {
      //切换流程分类 重置子类
      setFieldsValue({
        flowChildType: e == 13 ? '7' : undefined,
      });
      this.setState({
        flowChildType: e == 13 ? '7' : undefined,
      });
    }
    this.props.dispatch({
      type: 'workFlowM/getFlowChildType',
      payload: {
        flowType: e,
      },
    });
  };
  handleChange = (e) => {
    if (e == 1) {
      //重新按照选择的流程模板渲染
      this.state.BPMNEditor.renderDiagram(diagramXML1, 'first');
    }
  };
  showForm() {
    const { type, modalData, flowNumberList } = this.props;
    const {
      form: { getFieldDecorator, getFieldValue },
      workFlowM: { flowChildTypeList = [] },
      globalM: {
        dataDictionary: { flow = [] },
      },
    } = this.props;
    const isDisabled = type == 'query' ? true : false;

    return (
      <div>
        <Form>
          <Row>
            <Col lg={6}>
              <FormItem {...FormItemLayout} label={'流程名称'}>
                {getFieldDecorator(
                  'flowName',
                  {
                    initialValue: modalData.flowName,
                    rules: [{ required: true, message: '流程名称不能为空!' }],
                  },
                  {},
                )(<Input disabled={isDisabled} maxLength={20} />)}
              </FormItem>
            </Col>
            <Col lg={6}>
              <SelectC
                form={this.props.form}
                title='业务流程分类'
                dataIndex='flowType'
                optionTitle={true}
                disabled={isDisabled}
                formItemLayout={FormItemLayout1}
                dataSource={
                  flow
                    ? flow.map((item) => {
                        return { title: item.value, value: item.code };
                      })
                    : []
                }
                onChange={(e) => {
                  this.getFlowChildTypeList(e, 'flowType');
                }}
                initialValue={modalData.flowType}
                rules={[{ required: true, message: '业务流程分类不能为空!' }]}
              />
            </Col>
            <Col lg={6}>
              <SelectC
                form={this.props.form}
                title='业务流程子类'
                dataIndex='flowChildType'
                allowClear={true}
                optionTitle={true}
                disabled={isDisabled}
                formItemLayout={FormItemLayout}
                dataSource={flowChildTypeList || []}
                initialValue={modalData.flowChildType}
                onChange={(e) => {
                  this.setState({ flowChildType: e });
                }}
                rules={[{ required: getFieldValue('flowType') == '13', message: '业务流程子类不能为空!' }]}
              />
            </Col>
            {type == 'add' ? (
              <Col lg={6}>
                <SelectC
                  form={this.props.form}
                  title='流程模板'
                  dataIndex='flowNumber'
                  optionTitle={true}
                  disabled={type != 'add' ? true : false}
                  formItemLayout={FormItemLayout2}
                  onChange={this.handleChange}
                  dataSource={flowNumberList || []}
                  initialValue={modalData.flowNumber}
                />
              </Col>
            ) : null}
          </Row>
        </Form>
      </div>
    );
  }

  showBpmn() {
    const { type, modalData } = this.props;
    const dom = document.querySelector('.workFlowModal .ant-modal-body');
    const currentHeight = dom ? dom.offsetHeight - 110 : '100%';
    return (
      <div>
        {type == 'query' ? (
          <div style={{ marginTop: '10px' }}>
            <BPMNViewer
              diagramXML={modalData.flowxml}
              //  height={currentHeight}
              isOrder={this.state.flowType == 13 && this.state.flowChildType == 7}
              flowType={this.state.flowType}
              flowChildType={this.state.flowChildType}
            />
          </div>
        ) : (
          <div style={{ marginTop: '10px' }}>
            <div style={{ height: currentHeight }}>
              <BPMNEditor
                diagramXML={modalData.flowxml || undefined}
                attributeData={this.state.data}
                height={currentHeight}
                onRef={(ref) => this.setState({ BPMNEditor: ref })}
                isOrder={this.state.flowType == 13 && this.state.flowChildType == 7}
                flowType={this.state.flowType}
                flowChildType={this.state.flowChildType}
              />
            </div>
          </div>
        )}
      </div>
    );
  }
  render() {
    const {
      dispatch,
      visibleModal,
      type,
      modalData,
      form: { validateFields, getFieldsValue },
    } = this.props;
    const modalProps = {
      visible: visibleModal,
      onOk: () => {
        let xml = '';
        this.state.BPMNEditor.handleSave((args) => {
          xml = args;
        });

        let url = type == 'add' ? 'workFlowM/addFlow' : 'workFlowM/editFlow';
        validateFields(['flowName', 'flowType', 'flowChildType', 'flowNumber'], (err, values) => {
          if (!err) {
            this.setState({
              //模态框loading开始
              isLoading: true,
            });
            dispatch({
              type: url,
              payload: {
                ...values,
                flowxml: xml,
                flowxmlName: `${uuid(6)}.bpmn20.xml`,
                flowNo: modalData.flowNo || undefined,
                flowChildType: values.flowChildType || undefined,
              },
              callback: (msg) => {
                this.setState({
                  //模态框loading结束
                  isLoading: false,
                });
                if (msg == 'success') {
                  this.props.triggerVisible(false); //关闭modal
                  this.props.onQuery();
                }
              },
            });
          }
        });
      },
      onCancel: () => {
        this.props.triggerVisible(false); //关闭modal
      },
      title: type == 'add' ? '新增' : type == 'edit' ? '修改' : '查看',
      className: 'workFlowModal',
      height: 500, //内容区域的高度
      width: 1200,
      maskClosable: false, // 点击蒙层是否允许关闭
      footer: type == 'query' ? null : undefined,
    };
    return (
      <ModalC {...modalProps}>
        <Spin spinning={this.state.isLoading}>
          {this.showForm()}
          {this.showBpmn()}
        </Spin>
      </ModalC>
    );
  }
}
